##this code constructs Figure 2 of Bassetto and Miller
##
rm(list = ls())
pacman::p_load(data.table,lubridate,ggplot2)
##
src <- "data/raw/google_search_080424.csv"
##
dt <- fread(src)
dt[,`inflation: (United States)` := NULL]

##now construct 12 month rolling averages for the variables of interest.
vars <- colnames(dt)[2:ncol(dt)]
avg_names <- gsub(":.*","",vars) #this removes all text after the colon

##
dt[,`inflation stimulus: (United States)` := as.numeric(`inflation stimulus: (United States)`)][
  is.na(`inflation stimulus: (United States)`),`inflation stimulus: (United States)` := 0] #this is for the entries that have a <1 column

avg = 12

dt[,paste0("12mavg_",avg_names) := frollmean(.SD,n = avg,algo = "exact"),.SDcols = vars]

dt2 <- melt(dt,measure = patterns("12mavg_*"),value.name = "value",variable.factor = FALSE)
dt2[,variable := gsub("12mavg_","",variable)][,max_val := max(value,na.rm = TRUE),by = "variable"]
dt2[,normalized := (value/max_val)*100]
dt2[,Month := ym(Month)]
dt2[,Term := variable]

##
##list tick marks
dates <- ym(c("200412","200901","201301","201701","202101","202406"))
dates_dashes <- yq(c(paste0(seq(2005,2024,by = 1),"Q1"),
                     #paste0(seq(2005,2024,by = 1),"Q2"),
                     paste0(seq(2005,2024,by = 1),"Q3")))
                     #paste0(seq(2005,2024,by = 1),"Q4")))

line_type <- 2

p1 <- ggplot(data = dt2[!is.na(normalized)],aes(x = Month,y = normalized,group = Term,color = Term)) + 
  geom_line(linetype = line_type,linewidth = 0.8) + 
  geom_point(data = dt2[Month %in% dates_dashes],aes(shape = Term),size = 2.5) + 
  xlab("Date") + 
  ylab("Index") +
  scale_x_date(breaks = dates,date_labels = "%Y-%m") +
  theme(legend.position = c(0.17,0.81),
        legend.key = element_rect(colour = NA, fill = NA),
        legend.background = element_rect(fill = NA),
        legend.title=element_text(size=14), 
        legend.text=element_text(size=12),
        axis.text=element_text(size = 12),
        axis.title=element_text(size=14),
        panel.background = element_rect(colour = NA,fill = NA),
        panel.grid.major = element_line(colour = "grey"),
        panel.grid.minor = element_line(colour = "grey"),
        axis.ticks = element_blank()) 
  

p1
##
ggsave("output/figure2.pdf",p1,width = 10,height = 6)